package com.tanhua.server.service;

import com.tanhua.commons.TanHuaException;
import com.tanhua.domain.db.*;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.SettingsVo;
import com.tanhua.domain.vo.UserInfoVoAge;
import com.tanhua.dubbo.api.BlackListApi;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SettingService {
    @Reference
    private SettingsApi settingsApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private BlackListApi blackListApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${tanhua.redisValidateCodeKeyPrefix}")
    private String redisValidateCodeKeyPrefix;

    public SettingsVo querySettings() {
        //获取登录用户Id
        User loginUser = UserHolder.getUser();
        Long loginUserId = UserHolder.getUserId();
        String userTxt = "你喜欢我吗";
        //获取用户的设置问题
        Question questionUser = questionApi.findQuestion(loginUserId);
        if (null != questionUser) {
            userTxt = questionUser.getTxt();
        }
        Settings settingUser = settingsApi.findSettings(loginUserId);
        SettingsVo settingsVo = new SettingsVo();
        if (null != settingUser) {
            BeanUtils.copyProperties(settingUser, settingsVo);
        }
        settingsVo.setStrangerQuestion(userTxt);
        settingsVo.setId(loginUserId);
        settingsVo.setPhone(loginUser.getMobile());
        return settingsVo;
    }

    public void saveSettings(SettingsVo settingsVo) {
        //获取用户id
        Long loginId = UserHolder.getUserId();
        Settings settings = new Settings();
        BeanUtils.copyProperties(settingsVo, settings);
        settings.setUserId(loginId);
        settingsApi.saveSettings(settings);
    }

    public void saveQuestion(Map<String, String> questionMap) {
        Question question = new Question();
        question.setUserId(UserHolder.getUserId());
        question.setTxt(questionMap.get("content"));
        questionApi.saveQuestion(question);
    }

    public PageResult biackList(Long page, Long pagesize) {
        //获取用户id
        Long loginId = UserHolder.getUserId();
        //获取用户的黑名单集合
        PageResult pageResult = blackListApi.findBlackList(loginId, page, pagesize);
        //遍历集合取出用户的id
        List<BlackList> items = pageResult.getItems();
//        根据id查询用户
        if (!CollectionUtils.isEmpty(items)) {
            List<Long> blackUserIds = items.stream().map(BlackList::getBlackUserId).collect(Collectors.toList());
//        查询用户信息
            ArrayList<UserInfoVoAge> userInfoVos = new ArrayList<>();
            for (Long blackUserId : blackUserIds) {
                UserInfo userById = userInfoApi.findUserById(blackUserId);
                UserInfoVoAge userInfoVoAge = new UserInfoVoAge();
                BeanUtils.copyProperties(userById, userInfoVoAge);
                userInfoVoAge.setAge(userById.getAge());
                userInfoVos.add(userInfoVoAge);
            }
            pageResult.setItems(userInfoVos);
        }
        //  返回pageresout
        return pageResult;
    }

    public void removeBlaceList(Long blackUserId) {
        Long loginId = UserHolder.getUserId();
        blackListApi.removeBlaceList(loginId, blackUserId);
    }

    public void sendVerificationCode() {
        User loginUser = UserHolder.getUser();
        String phone = loginUser.getMobile();
        String key = redisValidateCodeKeyPrefix + phone;
        //获取验证码
        String codeInRedis = stringRedisTemplate.opsForValue().get(key);
        log.info("codeInRedis:{},{}", codeInRedis, phone);
        //查询验证码
        if (null != codeInRedis) {
            throw new TanHuaException(ErrorResult.duplicate());
        } else {
            //随机验证码
            //String validateCode = RandomStringUtils.randomNumeric(6);
            String validateCode = "123456";
            //   Map<String, String> sendResult = smsTemplate.sendValidateCode(phone, validateCode);

            //如果为返回不为空发送失败
            //    if (null != sendResult) {
            if (false) {
                throw new TanHuaException(ErrorResult.fail());
            }
            log.info("发送验证成功:{},{}", phone, validateCode);
            stringRedisTemplate.opsForValue().set(key, validateCode, 10, TimeUnit.MINUTES);
        }

    }

    public boolean checkValidateCode(String checkValidateCode) {
        User loginUser = UserHolder.getUser();
        String phone = loginUser.getMobile();
        //通过手机号生成验证码
        String key = redisValidateCodeKeyPrefix + phone;
        //通过手机号从redis查询验证码
        String codeInRedis = stringRedisTemplate.opsForValue().get(key);
        log.info("codeInRedis:{},{}", codeInRedis, phone);
        //如果不存在验证码说明验证码已经失效重新申请验证码
        if (StringUtils.isEmpty(codeInRedis)) {
            throw new TanHuaException(ErrorResult.loginError());
        }
        //如果存在验证码就开始校验
        if (!StringUtils.isEquals(codeInRedis, checkValidateCode)) {
            return false;
        }
        //删除key
        stringRedisTemplate.delete(key);
        return true;
    }

    public void changMobile(String phone) {
        Long loginUSerId = UserHolder.getUserId();
        settingsApi.changMobile(phone,loginUSerId);
    }
}
